package com.exp.security.config;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangxj
 * @date 2025/1/4
 * @Description 自定义认证成功处理器
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");

        // 用户信息
        Object principal = authentication.getPrincipal();
        // 用户凭证 - 一般指密码
        Object credentials = authentication.getCredentials();

        // 将结果转换成 json 字符串
        Map<String, Object> result = new HashMap();
        result.put("code", 200);
        result.put("msg", "登录成功");
        result.put("data", principal);
        String responseJson = JSONUtil.toJsonStr(result);
        response.getWriter().write(responseJson);
    }
}
